package utilities.event;

import hibernatesrc.billStream.ConcreteBill;
import hibernatesrc.billStream.Service;
import hibernatesrc.billStream.ServiceRec;
import hibernatesrc.hibernateInterface.BillSystemHibernateInterface;

import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.hibernate.Session;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;

import utilities.Updatable;
import utilities.utilities_components.Duration;
import utilities.utilities_components.RoomTypeController;

public class RILListener implements EventListener{
	private Duration duration;
	private RoomTypeController roomTypeController;
	private Updatable updateItem;
	
	public RILListener( Duration duration, RoomTypeController roomTypeController, Updatable updateItem ){
		this.duration = duration;
		this.roomTypeController = roomTypeController;
		this.updateItem = updateItem;
	}
	
	public void onEvent( Event event ){
		Date begin = duration.getBegin();
		if( begin != null ){
			Date end = duration.getEnd();
			
			updateItem.update( getData( begin, end, roomTypeController.getSelectedItem() ), session );
		}
	}
	
	/*  返回一个List, List中元素仍为保存有行信息的List,从左到右,各列信息如下:
	 * "房号", "入账时间", "止记时间", "钟房", "折扣价", "加床费", "数量", "金额", 
	 * "当时房型", "帐单号"
	 * 
	 * 参数:
	 * begin: 查询数据的起始时间
	 * end: 查询数据的终止时间
	 * roomType: 查询房型, 0-所用房型, 1-计天房, 2-钟点房
	 */
	private List getData(Date begin,Date end,int roomType,Session session){
		
		List billList=BillSystemHibernateInterface.getBillByTime(begin,end,ConcreteBill.getClass());
		Iterator itr=billList.iterator();
		ConcreteBill temp=null;
		Service addBedService=Service.getService("加床费");
		
		LinkedList ret=new LinkedList();
		LinkedList col=null;
		while(itr.hasNext()){
			temp=(ConcreteBill)itr.next();
			col=new LinkedList();
			
			//primary info
			col.addLast(temp.getAssociatedRoom().getRoomNumber());
			col.addLast(temp.getTimeCreate());
			col.addLast(temp.getTimePay());
			col.addList(temp.getCountByHour() ? "是" : "否");
			
			//add the service info of adding beds
			if(addBedService != null){
				Iterator itr2=temp.getServiceList().iterator();
				ServiceRec record=null;
				boolean found=false;
				while(itr2.hasNext()){
					record=(ServiceRec)itr2.next();
					if(record.getService().getInner() == addBedService){
						col.add(record.getService().getInner().getPricePerUnit().getFirst().toString());
						col.add(record.getPiece());
						col.add(record.getPrice());
						found=true;
						break;
					}
					if(!found){
						col.add("0");
						col.add("0");
						col.add("0");
					}
				}
			}
			
			col.add(record.getAssociatedRoom().getRoomType().getSizeAndFacilities().toString());
			col.add(record.getId());
			ret.add(col);
		}
		
		return ret;
	}
}
